package cyou.breathe.dynamictp.core.notification.service;

import cyou.breathe.dynamictp.core.config.BootstrapConfigProperties;
import cyou.breathe.dynamictp.core.notification.dto.ThreadPoolAlarmNotifyDTO;
import cyou.breathe.dynamictp.core.notification.dto.ThreadPoolConfigChangeDTO;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @author: breathe
 * @createTime: 2025-09-15
 */
public class NotifierDispatcher implements NotifierService {

    private static final Map<String, NotifierService> NOTIFIER_SERVICE_MAP = new HashMap<>();

    static {
        NOTIFIER_SERVICE_MAP.put("DING", new DingTalkMessageService());
        NOTIFIER_SERVICE_MAP.put("LARK", new LarkMessageService());
    }

    @Override
    public void sendChangeMessage(ThreadPoolConfigChangeDTO configChange) {
        Optional<NotifierService> notifierService = Optional.ofNullable(BootstrapConfigProperties.getInstance().getNotifyPlatforms())
                .map(BootstrapConfigProperties.NotifyPlatformsConfig::getPlatform)
                .map(each -> NOTIFIER_SERVICE_MAP.get(each));
        if (notifierService.isPresent()) {
            notifierService.get().sendChangeMessage(configChange);
        }
    }

    @Override
    public void sendAlarmMessage(ThreadPoolAlarmNotifyDTO alarm) {
        Optional<NotifierService> notifierService = Optional.ofNullable(BootstrapConfigProperties.getInstance().getNotifyPlatforms())
                .map(BootstrapConfigProperties.NotifyPlatformsConfig::getPlatform)
                .map(each -> NOTIFIER_SERVICE_MAP.get(each));
        if (notifierService.isPresent()) {
            // 频率检查
            boolean allowSend = AlarmRateLimiter.allowAlarm(
                    alarm.getThreadPoolId(),
                    alarm.getAlarmType(),
                    alarm.getInterval()
            );

            // 满足频率发送告警
            if (allowSend) {
                notifierService.get().sendAlarmMessage(alarm);
            }
        }
    }
}

